package com.basemanage.core.auth.interceptor;

import java.io.PrintWriter;
import java.io.StringWriter;

import com.basemanage.core.util.CommonUtils;
import com.basemanage.model.SysLog;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.LogKit;

/**
 * 日志拦截器
 */
public class SysLogInterceptor implements Interceptor {
	
	public void intercept(Invocation inv) {
		String from=inv.getController().getRequest().getHeader("Referer");
		String ip=CommonUtils.getIP(inv.getController().getRequest());
		String className=inv.getController().getClass().getName();
		String methodName=inv.getMethodName();
		Integer uid=null;
		long startTime=System.currentTimeMillis();
		try{
			inv.invoke();
			SysLog.dao.saveSysLog(uid, ip, from, inv.getActionKey(), className, methodName, startTime, 0,"");
		}catch(RuntimeException e){
			LogKit.error(getExceptionAllinformation(e));
			SysLog.dao.saveSysLog(uid, ip, from, inv.getActionKey(), className, methodName, startTime, -1,e.getMessage());
		}
	}
	 /**
	  * 获取异常详细信息
	  */
	  private static String getExceptionAllinformation(Throwable e){   
          StringWriter sw = new StringWriter();   
          PrintWriter pw = new PrintWriter(sw, true);   
          e.printStackTrace(pw);   
          pw.flush();   
          sw.flush();   
          return sw.toString();   
	  } 
}
